package com.starrocks.controller;

import com.starrocks.common.Result;
import com.starrocks.service.IncrementalSyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 增量同步控制器
 * 提供增量同步管理接口
 */
@Slf4j
@RestController
@RequestMapping("/api/sync")
public class SyncController {

    @Autowired
    private IncrementalSyncService incrementalSyncService;

    /**
     * 启动增量同步
     */
    @PostMapping("/start")
    public Result<String> startSync() {
        try {
            incrementalSyncService.startSync();
            return Result.success("增量同步服务已启动", "INCREMENTAL_SYNC");
        } catch (Exception e) {
            log.error("启动增量同步失败", e);
            return Result.error("启动失败：" + e.getMessage());
        }
    }

    /**
     * 停止增量同步
     */
    @PostMapping("/stop")
    public Result<Void> stopSync() {
        try {
            incrementalSyncService.stopSync();
            return Result.success("增量同步服务已停止", null);
        } catch (Exception e) {
            log.error("停止增量同步失败", e);
            return Result.error("停止失败：" + e.getMessage());
        }
    }

    /**
     * 获取同步状态
     */
    @GetMapping("/status")
    public Result<Map<String, Object>> getStatus() {
        try {
            Map<String, Object> status = incrementalSyncService.getSyncStatus();
            return Result.success(status);
        } catch (Exception e) {
            log.error("获取同步状态失败", e);
            return Result.error("获取状态失败：" + e.getMessage());
        }
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public Result<Map<String, Object>> health() {
        try {
            Map<String, Object> healthInfo = new HashMap<String, Object>(){{
                put("status", incrementalSyncService.isRunning() ? "RUNNING" : "STOPPED");
                put("service", "StarRocks Incremental Sync Service");
                put("mode", "INCREMENTAL");
            }};
            return Result.success(healthInfo);
        } catch (Exception e) {
            log.error("健康检查失败", e);
            return Result.error("健康检查失败：" + e.getMessage());
        }
    }

    /**
     * 重置表的同步时间点
     * 
     * @param tableName 表名
     * @param syncTime 同步时间点（格式：2025-10-29T00:00:00）
     */
    @PostMapping("/reset-time/{tableName}")
    public Result<Void> resetSyncTime(
            @PathVariable String tableName,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncTime) {
        try {
            incrementalSyncService.resetSyncTime(tableName, syncTime);
            return Result.success("表 " + tableName + " 的同步时间点已重置为：" + syncTime, null);
        } catch (Exception e) {
            log.error("重置同步时间点失败", e);
            return Result.error("重置失败：" + e.getMessage());
        }
    }
    
    /**
     * 重新加载同步配置（热加载）
     * 配置更新后调用此接口使其生效
     */
    @PostMapping("/reload-config")
    public Result<Void> reloadConfig() {
        try {
            incrementalSyncService.reloadConfigs();
            return Result.success("配置已重新加载", null);
        } catch (Exception e) {
            log.error("重新加载配置失败", e);
            return Result.error("重新加载失败：" + e.getMessage());
        }
    }
}
